<?php

namespace humhub\modules\api\controllers;

use humhub\modules\api\models\Tag;
use humhub\modules\api\models\UserTag;
use humhub\modules\user\models\User;
use humhub\modules\post\models\Post;
use Yii;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 用户标签管理  找人功能接口
 */
class UserTagController extends Base4Controller
{
    /**
     * 加入用户权限
     *
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        return $behaviors;
    }

    /**
     * 用户标签添加 更新 每次传入所有标签
     *
     * post api/user-tag/add
     *
     * post.tag  string 多个tag以 , 进行连接 标签名称
     *
     *@return boolean true 添加成功
     */
    public function actionAdd()
    {
        $tag=new Tag();
        $name=Yii::$app->request->post('tag');
        $uid=Yii::$app->user->id;
        $data=explode(',',$name);
        if($data){
            foreach ($data as $item){
                $_tag = clone $tag; //克隆对象
                $_tag->name=$item;
                $_tag->save();
            }
        }else{
            return false;
        }

        $ut=new UserTag();
        $ut->deleteAll(['user_id'=>$uid]);
        foreach ($data as $v){
            $id=Tag::find()->select('id')->where(['name'=>$v])->one();
            $_ut = clone $ut;
            $_ut->tag_id=$id['id'];
            $_ut->user_id=$uid;
            $_ut->save();

        }
        return true;
    }

    /**
     * 获得当前用户的所有标签
     *
     * get api/user-tag/get
     *
     * get.id  string 当前用户的id
     *
     *@return array 当前用户拥有的所有标签 没有标签返回[]
     */
    public function actionGet(){
        $id=(int)yii::$app->request->get('id');
        if($id){
            $data=UserTag::find()->select('tag_id')->where(['user_id'=>$id])->asArray()->all();
            if($data){
                foreach ($data as $v){
                    $tag=Tag::find()->select('name')->where(['id'=>$v])->one();
                    $da[]=$tag['name'];
                }
                    return $da;
            }else{
                return array();
            }
        }else{
            return false;
        }
    }

    /**
     * 获取搜索页用户推荐数据
     *
     * get api/user-tag/hot
     *
     *@return array 用户数据， uni 达人数据  new 新用户数据  habit 志趣相似用户数据
     */
    public function actionHot(){
        $uni=$this->actionUniv();
//        return $uni;
        $new=$this->actionNew();
        $habit=$this->actionHabit();
        return array(
            'uni'=>$uni,
            'new'=>$new,
            'habit'=>$habit
        );
    }

    /**
     * 志趣相投的用户
     *
     * get api/user-tag/habit
     *
     * get.post=post  固定值
     *
     *@return array 用户数据
     */
    public function actionHabit(){
        $uid=yii::$app->user->id;
        if(!$uid){
            return $u=[];
        }
        $names=SELF::getTid($uid);
//        return $names;
        if (!$names) return $u=[];
        $post=Yii::$app->request->get('post');
        if($post=='post'){
            $query=UserTag::find();
            $query->where(['in','tag_id',$names]);
            $query->groupBy('user_id');

            $pagination = new \yii\data\Pagination([
                'defaultPageSize' => 20,
                'validatePage' => false,
            ]);

            $users = $query->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();

            $u = [];$data=[];
            foreach($users as $user){
                $data[]=$user->user_id;
            }
//            return $data;
            foreach ($data as $k=>$v){
                if ($v === $uid)
                    unset($data[$k]);
            }
            if($data!=[]){
                foreach ($data as $item){
                    $user=User::findOne($item);
                    $u[]=SELF::getUser($user);
                }
            }

            return $u;
        }else{
            $data=UserTag::find()->where(['in','tag_id',$names])->groupBy('user_id')->limit(3)->all();
            if ($data){
                foreach ($data as $v){
                    $da[]=$v['user_id'];
                }
                    foreach ($da as $key=>$value)
                    {
                        if ($value === $uid)
                            unset($da[$key]);
                    }
//            return $da;
                    foreach ($da as $item){
                        $user=User::findOne($item);
                        $u[]=SELF::getUser($user);
                    }
                    return $u;
            }
            return [];

        }



    }

    /**
     * 新作品用户数据
     *
     * get api/user-tag/new
     *
     * get.post=post  固定值
     *
     *@return array 用户数据
     */
    public function actionNew(){
        $uid=yii::$app->user->id;
        if(!$uid){
            $uid=[];
        }
        $post=Yii::$app->request->get('post');
        if($post=='post'){
            $query=Post::find();
            $query->where(['<>','created_by',$uid]);
            $query->orderBy('created_at DESC');
            $query->groupBy('created_by');

//            $query->active();

            $pagination = new \yii\data\Pagination([
                'defaultPageSize' => 20,
                'validatePage' => false,
            ]);

            $users = $query->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();

            $u = [];
                foreach ($users as $item){
                    $user=User::findOne($item->created_by);
                    $u[]=SELF::getUser($user);
                }
            return $u;
        }else{
            $u=[];
            $data= Post::find()->select('created_by')
                ->where(['<>','created_by',$uid])
                ->orderBy('created_at DESC')
                ->groupBy('created_by')
                ->limit(3)
                ->all();

            foreach ($data as $item){
                $user=User::findOne($item);
                $u[]=SELF::getUser($user);
            }
            return $u;
        }


    }

    /**
     * uni达人用户数据
     *
     * get api/user-tag/univ
     *
     * get.post=post  固定值
     *
     *@return array 用户数据
     */
    public function actionUniv(){
        $uid=(int)yii::$app->user->id;
        if(!$uid){
            $uid=[];
        }
        $post=Yii::$app->request->get('post');
        if($post=='post'){
            $query=User::find();
            $query->where(['u_v'=>1]);
            $query->andWhere(['<>','id',$uid]);
            $query->orderBy('last_login DESC');

            $pagination = new \yii\data\Pagination([
                'defaultPageSize' => 20,
                'validatePage' => false,
            ]);

            $users = $query->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();

            $u = [];
            foreach($users AS $user){
                $u[]=SELF::getUser($user);
            }
            return $u;
        }else{
            $u=[];
            $data= User::find()
                ->where(['u_v'=>1])
                ->andWhere(['<>','id',$uid])
                ->orderBy('last_login DESC')
                ->limit(3)
                ->all();
            foreach ($data as $item){
                $u[]=$this->getUser($item);
            }
            return $u;
        }

    }

    /**
     * 获得默认推荐标签
     *
     * get api/user-tag/guide
     *
     *@return array 默认推荐标签
     */
    public function actionGuide(){
        return [
            ['name'=>'时尚','url'=>'http://www.uni-class.com/img/tager/6.png'],
            ['name'=>'艺术','url'=>'http://www.uni-class.com/img/tager/8.png'],
            ['name'=>'设计','url'=>'http://www.uni-class.com/img/tager/4.png'],
            ['name'=>'美学','url'=>'http://www.uni-class.com/img/tager/9.png'],
            ['name'=>'国际学校','url'=>'http://www.uni-class.com/img/tager/3.png'],
            ['name'=>'国际工坊','url'=>'http://www.uni-class.com/img/tager/2.png'],
            ['name'=>'奢侈品牌','url'=>'http://www.uni-class.com/img/tager/5.png'],
            ['name'=>'国际大师','url'=>'http://www.uni-class.com/img/tager/1.png'],
            ['name'=>'时尚明星','url'=>'http://www.uni-class.com/img/tager/7.png']
        ];
    }

    //获取标签id
    private function getTid($id){
            $data=UserTag::find()->select('tag_id')->where(['user_id'=>$id])->asArray()->all();
            if($data){
                return $data;
            }else{
                return array();
            }
    }
    //根据标签id获取标签名称
    private function getTname($data=[]){
        $da=[];
        foreach ($data as $v){
            $tag=Tag::find()->select('name')->where(['id'=>$v])->one();
            $da[]=$tag['name'];
        }
        return $da;
    }
    //获取用户数据
    private function getUser($user){
        $uone['guid'] = $user->guid;
        $uone['profileimage'] = $user->getProfileImage()->getUrl();
        $uone['displayname'] = $user->displayName;
        $uone['title']   = $user->profile->title;
        $uone['follow']  = \humhub\modules\api\models\Follow::getFollow($user);
        $uone['countFollowers'] = $user->getFollowerCount();
//        $uone['tags'] = $tags;
        $uone['u_v']  = $user->u_v;
        return $uone;
    }

}

